//
//  WXPay.m
//  SXH
//
//  Created by Jack on 15/10/8.
//  Copyright © 2015年 lyss. All rights reserved.
//

#import "WXPay.h"
//APP端签名相关头文件
#import "payRequsestHandler.h"
//服务端签名只需要用到下面一个头文件
//#import "ApiXml.h"
#import <QuartzCore/QuartzCore.h>
#import "OrderEntity.h"

@interface WXPay()
@property (nonatomic,strong) BaseViewController *baseVC;
@end
@implementation WXPay

- (id)init{
    if(self = [super init]){
        //向微信注册
        [WXApi registerApp:APP_ID withDescription:@"demo 2.0"];
    }
    return self;
}

-(void) onResp:(BaseResp*)resp
{
    NSString *strMsg = [NSString stringWithFormat:@"errcode:%d", resp.errCode];
    NSString *strTitle;
    
    if([resp isKindOfClass:[SendMessageToWXResp class]])
    {
        strTitle = [NSString stringWithFormat:@"发送媒体消息结果"];
    }
    if([resp isKindOfClass:[PayResp class]]){
        //支付返回结果，实际支付结果需要去微信服务器端查询
        strTitle = [NSString stringWithFormat:@"支付结果"];
        
        //获取本地订单信息
        NSUserDefaults *orderDefault = [NSUserDefaults standardUserDefaults];
        NSMutableArray *mutableArrayTemp = [NSMutableArray arrayWithArray:[orderDefault objectForKey:@"OrderEntityList"]];
        
        switch (resp.errCode) {
            case WXSuccess:{
                strMsg = @"支付结果：成功！";
                NSLog(@"支付成功－PaySuccess，retcode = %d", resp.errCode);
                //删除本地订单
                for(int i=0;i<[mutableArrayTemp count];i++){
                    OrderEntity *orderEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayTemp objectAtIndex:i]];
                    if([orderEntity.status isEqualToString: @"9000"]){
                        [mutableArrayTemp removeObjectAtIndex:i];
                    }
                }
                //发送通知
                NSNotification *notification = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"9000"];
                [[NSNotificationCenter defaultCenter] postNotification:notification];
                break;}
                
            default:{
                strMsg = [NSString stringWithFormat:@"支付结果：失败！retcode = %d, retstr = %@", resp.errCode,resp.errStr];
                NSLog(@"错误，retcode = %d, retstr = %@", resp.errCode,resp.errStr);
                //标记本地待支付订单
                for(int i=0;i<[mutableArrayTemp count];i++){
                    OrderEntity *orderEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayTemp objectAtIndex:i]];
                    if([orderEntity.status isEqualToString: @"9000"]){
                        orderEntity.status = @"1";
                        NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:orderEntity];
                        [mutableArrayTemp replaceObjectAtIndex:i withObject:newData];
                    }
                }
                NSNotification *notification2 = [NSNotification notificationWithName:@"ORDER_PAY_NOTIFICATION" object:@"6001"];
                [[NSNotificationCenter defaultCenter] postNotification:notification2];
                break;}
        }
        
        //记住要转换成不可变数组类型
        NSArray * array = [NSArray arrayWithArray:mutableArrayTemp];
        [orderDefault setObject:array forKey:@"OrderEntityList"];
        
    }
    //    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:strTitle message:strMsg delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    //    [alert show];
}

//============================================================
// V3&V4支付流程实现
// 注意:参数配置请查看服务器端Demo
// 更新时间：2015年3月3日
// 负责人：李启波（marcyli）
//============================================================
- (void)sendPayDemo:(NSString *)tradeNO productName:(NSString *)productName amount:(NSString *)amount VC:(BaseViewController *)vc
{
    if(![WXApi isWXAppInstalled]){
        [self alert:@"提示信息" msg:@"您还没有安装微信"];
        return;
    }
    
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [payRequsestHandler alloc];
    //初始化支付签名对象
    [req init:APP_ID mch_id:MCH_ID];
    //设置密钥
    [req setKey:PARTNER_ID];
    
    //}}}
    
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo:productName amount:amount];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [self alert:@"提示信息" msg:debug];
        
        NSLog(@"%@\n\n",debug);
    }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        self.baseVC=vc;
        //标记本地待支付订单
        NSUserDefaults *orderDefault = [NSUserDefaults standardUserDefaults];
        NSMutableArray *mutableArrayTemp = [NSMutableArray arrayWithArray:[orderDefault objectForKey:@"OrderEntityList"]];
        for(int i=0;i<[mutableArrayTemp count];i++){
            OrderEntity *orderEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayTemp objectAtIndex:i]];
            if([orderEntity.order_num isEqualToString: tradeNO]){
                orderEntity.status = @"9000";
                NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:orderEntity];
                [mutableArrayTemp replaceObjectAtIndex:i withObject:newData];
            }
        }
        //记住要转换成不可变数组类型
        NSArray * array = [NSArray arrayWithArray:mutableArrayTemp];
        [orderDefault setObject:array forKey:@"OrderEntityList"];
        
        
        [WXApi sendReq:req];
    }
}

- (void)sendPay:(NSDictionary *)dict VC:(BaseViewController *)vc
{
    NSUserDefaults *wxBlockDict = [NSUserDefaults standardUserDefaults];
    [wxBlockDict setObject:dict forKey:@"wxBlockDict"];
    
    if(![WXApi isWXAppInstalled]){
        [self alert:@"提示信息" msg:@"您还没有安装微信"];
        return;
    }
    if(dict != nil){
        NSMutableString *retcode = [dict objectForKey:@"code"];
        if (retcode.intValue == 0){
            NSMutableString *stamp  = [dict objectForKey:@"timeStamp"];
            
            //调起微信支付
            PayReq* req             = [[PayReq alloc] init];
            req.openID              = APP_ID;
            req.partnerId           = MCH_ID;
            req.prepayId            = [dict objectForKey:@"prepayId"];
            req.nonceStr            = [dict objectForKey:@"nonceStr"];
            req.timeStamp           = stamp.intValue;
            req.package             = @"Sign=WXPay";
            req.sign                = [dict objectForKey:@"sign"];
            
            //            self.baseVC=vc;
            //标记本地待支付订单
            NSUserDefaults *orderDefault = [NSUserDefaults standardUserDefaults];
            NSMutableArray *mutableArrayTemp = [NSMutableArray arrayWithArray:[orderDefault objectForKey:@"OrderEntityList"]];
            for(int i=0;i<[mutableArrayTemp count];i++){
                OrderEntity *orderEntity = [NSKeyedUnarchiver unarchiveObjectWithData:[mutableArrayTemp objectAtIndex:i]];
                if([orderEntity.order_num isEqualToString: [dict objectForKey:@"order_num"]]){
                    orderEntity.status = @"9000";
                    NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:orderEntity];
                    [mutableArrayTemp replaceObjectAtIndex:i withObject:newData];
                }
            }
            //记住要转换成不可变数组类型
            NSArray * array = [NSArray arrayWithArray:mutableArrayTemp];
            [orderDefault setObject:array forKey:@"OrderEntityList"];
            
            
            [WXApi sendReq:req];
            //            [WXApi safeSendReq:req];
            
            //日志输出
            NSLog(@"appid=%@\npartid=%@\nprepayid=%@\nnoncestr=%@\ntimestamp=%ld\npackage=%@\nsign=%@",req.openID,req.partnerId,req.prepayId,req.nonceStr,(long)req.timeStamp,req.package,req.sign );
        }else{
            //            [self alert:@"提示信息" msg:[dict objectForKey:@"retmsg"]];
        }
    }
}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
}


@end
